#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

class tcpClient
{
public:
    tcpClient(std::string ip, uint16_t port)
        : _sockfd(-1), _serverip(ip), _serverport(port)
    {
    }
    void initClient()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            exit(1);
        }
    }
    void run()
    {
        struct sockaddr_in peer;
        peer.sin_family = AF_INET;
        peer.sin_port = htons(_serverport);
        peer.sin_addr.s_addr = inet_addr(_serverip.c_str());

        int n = connect(_sockfd, (struct sockaddr*)&peer, sizeof(peer));
        if(n < 0)
        {
            std::cerr << "connect failed" << std::endl;
            exit(2);
        }
        while(true)
        {
            std::cout << "Please Enter#";
            std::string message;
            getline(std::cin, message);
            write(_sockfd, message.c_str(), message.size());

            char buffer[1024];
            int n = read(_sockfd, buffer, sizeof(buffer) - 1);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout << "Server# " << buffer << std::endl;

            }
            else
            {
                break;
            }


        }
    }
    ~tcpClient()
    {
    }

private:
    int _sockfd;
    std::string _serverip;
    uint16_t _serverport;
};
